package com.db.concurrency.pool;

import java.sql.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class RegulatingConnectionPool implements ConnectionPool {
    private static final int CLEAN_PERIOD_SEC = 10;
    private static final int MAX_FREE_CONN_COUNT = 3;
    private final String url;
    private final String user;
    private final String pwd;
    private final int min;
    private final int max;
    private volatile int used;
    private volatile int allocated;
    private final Lock lock = new ReentrantLock();
    private final Semaphore available;
    private final Map<Connection, Boolean> usageMap;
    private final Runnable cleaner = new Cleaner();
    private final ScheduledExecutorService cleanScheduler = Executors.newSingleThreadScheduledExecutor();

    public RegulatingConnectionPool(String url, String user, String pwd, String driverClassName, int min, int max) throws SQLException, ClassNotFoundException {
        this.url = url;
        this.user = user;
        this.pwd = pwd;
        Class.forName(driverClassName);
        this.min = min;
        this.max = max;
        this.available = new Semaphore(max, true);
        this.usageMap = new HashMap<Connection, Boolean>(max);
        for (int i = 0; i < min; ++i) {
            allocateConnection();
        }
        this.cleanScheduler.scheduleAtFixedRate(cleaner, 0, CLEAN_PERIOD_SEC, TimeUnit.SECONDS);
    }

    public int getUsed() {
        return used;
    }

    public int getAllocated() {
        return allocated;
    }

    public void close() throws Exception {
        cleanScheduler.shutdownNow();
        for (Map.Entry<Connection, Boolean> entry : usageMap.entrySet()) {
            entry.getKey().close();
        }
    }

    private void release(Connection connection) {
        if (markAsUnused(connection)) {
            available.release();
        }
    }

    private boolean markAsUnused(Connection connection) {
        lock.lock();
        try {
            if (usageMap.containsKey(connection)) {
                boolean isUsed = !usageMap.put(connection, true);
                if (isUsed) {
                    used--;
                }
                return isUsed;
            }
            return false;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Connection getConnection() {
        try {
            available.acquire();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
        return getNextAvailableConnection();
    }

    private Connection getNextAvailableConnection() {
        lock.lock();
        try {
            if (needAllocate()) {
                allocateConnection();
            }
            for (Map.Entry<Connection, Boolean> entry : usageMap.entrySet()) {
                if (entry.getValue()) {
                    entry.setValue(false);
                    used++;
                    return new MyConnection(this, entry.getKey());
                }
            }
            return null; // not reached
        } finally {
            lock.unlock();
        }
    }

    private boolean needAllocate() {
        return allocated == used && used < max;
    }

    private void allocateConnection() {
        try {
            usageMap.put(DriverManager.getConnection(url, user, pwd), true);
            allocated++;
        } catch (SQLException sqlException) {
            throw new RuntimeException("Can't allocate connection", sqlException);
        }
    }

    @Override
    public Connection tryGetConnection() {
        return available.tryAcquire() ? getNextAvailableConnection() : null;
    }

    @Override
    public Connection tryGetConnection(long timeout, TimeUnit timeUnit) throws InterruptedException {
        return available.tryAcquire(timeout, timeUnit) ? getNextAvailableConnection() : null;
    }

    private class Cleaner implements Runnable {
        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println("Start cleaning...");
                Iterator<Map.Entry<Connection, Boolean>> iterator = usageMap.entrySet().iterator();
                Map.Entry<Connection, Boolean> entry;
                while (iterator.hasNext()) {
                    entry = iterator.next();
                    if (needClean()) {
                        if (entry.getValue()) {
                            entry.getKey().close();
                            iterator.remove();
                            allocated--;
                        }
                    } else {
                        System.out.println("Cleaning finished");
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        private boolean needClean() {
            return allocated > min && allocated > used + MAX_FREE_CONN_COUNT;
        }
    }

    private static class MyConnection implements Connection {
        private final RegulatingConnectionPool pool;
        private final Connection connection;
        private boolean isClosed;

        private MyConnection(RegulatingConnectionPool pool, Connection connection) {
            this.pool = pool;
            this.connection = connection;
        }

        private void checkState() throws SQLException {
            if (isClosed) {
                throw new SQLException("connection is closed");
            }
        }

        private void checkState2() throws SQLClientInfoException {
            if (isClosed) {
                throw new SQLClientInfoException(null);
            }
        }

        @Override
        public Statement createStatement() throws SQLException {
            checkState();
            return connection.createStatement();
        }

        @Override
        public PreparedStatement prepareStatement(String sql) throws SQLException {
            checkState();
            return connection.prepareStatement(sql);
        }

        @Override
        public CallableStatement prepareCall(String sql) throws SQLException {
            checkState();
            return connection.prepareCall(sql);
        }

        @Override
        public String nativeSQL(String sql) throws SQLException {
            checkState();
            return connection.nativeSQL(sql);
        }

        @Override
        public void setAutoCommit(boolean autoCommit) throws SQLException {
            checkState();
            connection.setAutoCommit(autoCommit);
        }

        @Override
        public boolean getAutoCommit() throws SQLException {
            return connection.getAutoCommit();
        }

        @Override
        public void commit() throws SQLException {
            checkState();
            connection.commit();
        }

        @Override
        public void rollback() throws SQLException {
            checkState();
            connection.rollback();
        }

        @Override
        public void close() throws SQLException {
            checkState();
            pool.release(connection);
            isClosed = true;
        }

        @Override
        public boolean isClosed() throws SQLException {
            checkState();
            return connection.isClosed();
        }

        @Override
        public DatabaseMetaData getMetaData() throws SQLException {
            checkState();
            return connection.getMetaData();
        }

        @Override
        public void setReadOnly(boolean readOnly) throws SQLException {
            checkState();
            connection.setReadOnly(readOnly);
        }

        @Override
        public boolean isReadOnly() throws SQLException {
            checkState();
            return connection.isReadOnly();
        }

        @Override
        public void setCatalog(String catalog) throws SQLException {
            checkState();
            connection.setCatalog(catalog);
        }

        @Override
        public String getCatalog() throws SQLException {
            checkState();
            return connection.getCatalog();
        }

        @Override
        public void setTransactionIsolation(int level) throws SQLException {
            checkState();
            connection.setTransactionIsolation(level);
        }

        @Override
        public int getTransactionIsolation() throws SQLException {
            checkState();
            return connection.getTransactionIsolation();
        }

        @Override
        public SQLWarning getWarnings() throws SQLException {
            checkState();
            return connection.getWarnings();
        }

        @Override
        public void clearWarnings() throws SQLException {
            checkState();
            connection.clearWarnings();
        }

        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
            checkState();
            return connection.createStatement(resultSetType, resultSetConcurrency);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            checkState();
            return connection.prepareStatement(sql, resultSetType, resultSetConcurrency);
        }

        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            checkState();
            return connection.prepareCall(sql, resultSetType, resultSetConcurrency);
        }

        @Override
        public Map<String, Class<?>> getTypeMap() throws SQLException {
            checkState();
            return connection.getTypeMap();
        }

        @Override
        public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
            checkState();
            connection.setTypeMap(map);
        }

        @Override
        public void setHoldability(int holdability) throws SQLException {
            checkState();
            connection.setHoldability(holdability);
        }

        @Override
        public int getHoldability() throws SQLException {
            checkState();
            return connection.getHoldability();
        }

        @Override
        public Savepoint setSavepoint() throws SQLException {
            checkState();
            return connection.setSavepoint();
        }

        @Override
        public Savepoint setSavepoint(String name) throws SQLException {
            checkState();
            return connection.setSavepoint(name);
        }

        @Override
        public void rollback(Savepoint savepoint) throws SQLException {
            checkState();
            connection.rollback(savepoint);
        }

        @Override
        public void releaseSavepoint(Savepoint savepoint) throws SQLException {
            checkState();
            connection.releaseSavepoint(savepoint);
        }

        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            checkState();
            return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            checkState();
            return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            checkState();
            return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
            checkState();
            return connection.prepareStatement(sql, autoGeneratedKeys);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
            checkState();
            return connection.prepareStatement(sql, columnIndexes);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
            checkState();
            return connection.prepareStatement(sql, columnNames);
        }

        @Override
        public Clob createClob() throws SQLException {
            checkState();
            return connection.createClob();
        }

        @Override
        public Blob createBlob() throws SQLException {
            checkState();
            return connection.createBlob();
        }

        @Override
        public NClob createNClob() throws SQLException {
            checkState();
            return connection.createNClob();
        }

        @Override
        public SQLXML createSQLXML() throws SQLException {
            checkState();
            return connection.createSQLXML();
        }

        @Override
        public boolean isValid(int timeout) throws SQLException {
            checkState();
            return connection.isValid(timeout);
        }

        @Override
        public void setClientInfo(String name, String value) throws SQLClientInfoException {
            checkState2();
            connection.setClientInfo(name, value);
        }

        @Override
        public void setClientInfo(Properties properties) throws SQLClientInfoException {
            checkState2();
            connection.setClientInfo(properties);
        }

        @Override
        public String getClientInfo(String name) throws SQLException {
            checkState();
            return connection.getClientInfo(name);
        }

        @Override
        public Properties getClientInfo() throws SQLException {
            checkState();
            return connection.getClientInfo();
        }

        @Override
        public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
            checkState();
            return connection.createArrayOf(typeName, elements);
        }

        @Override
        public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
            checkState();
            return connection.createStruct(typeName, attributes);
        }

        @Override
        public void setSchema(String schema) throws SQLException {
            checkState();
            connection.setSchema(schema);
        }

        @Override
        public String getSchema() throws SQLException {
            checkState();
            return connection.getSchema();
        }

        @Override
        public void abort(Executor executor) throws SQLException {
            checkState();
            connection.abort(executor);
        }

        @Override
        public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
            checkState();
            connection.setNetworkTimeout(executor, milliseconds);
        }

        @Override
        public int getNetworkTimeout() throws SQLException {
            checkState();
            return connection.getNetworkTimeout();
        }

        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            checkState();
            return connection.unwrap(iface);
        }

        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            checkState();
            return connection.isWrapperFor(iface);
        }
    }
}
